package com.rockcent.api.controller;

import com.rockcent.api.Routes;
import com.rockcent.api.helper.UserHelper;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.utils.DateUtils;
import com.rockcent.helper.SysMessageHelper;
import com.rockcent.mall.lib.constants.SysMessageConstants;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.AuditStatus;
import com.rockcent.mall.lib.domain.enumclass.MerchantPayType;
import com.rockcent.mall.lib.domain.enumclass.MerchantRechargeStatus;
import com.rockcent.mall.lib.domain.enumclass.SysMessageType;
import com.rockcent.mall.lib.dto.MerchantRechargeFlowDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.repository.MerchantFundRepository;
import com.rockcent.mall.lib.repository.MerchantRechargeFlowRepository;
import com.rockcent.mall.lib.repository.MerchantRepository;
import com.rockcent.service.MallSrv;
import com.rockcent.service.MerchantRechargeFlowSrv;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.Date;

/**
 * Created by DK on 17/3/28.
 * 商家充值审核管理
 */
@RestController
@RequestMapping(value = Routes.API_VERSION)
public class MerchantRechargeAuditController extends BaseController{
    private final Logger log = LoggerFactory.getLogger(MerchantRechargeAuditController.class);
    @Autowired
    private UserHelper userHelper;
    @Autowired
    private MerchantRechargeFlowRepository merchantRechargeFlowRepository;

    @Autowired
    private MerchantRepository merchantRepository;

    @Autowired
    private MerchantFundRepository merchantFundRepository;

    @Autowired
    private MerchantRechargeFlowSrv merchantRechargeFlowSrv;

    @Autowired
    private MallSrv mallSrv;

    /**
     * @api {get} /v1/merchant/recharge/audit_page M 商家充值审核分页
     * @apiGroup MERCHANT_RECHARGE
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} rechargeStatus <code>必选参数</code> 状态 ：WAIT("待审核"),AUDITED("已审核或者全部状态"), SUCCESS("审核通过"),FAIL("审核不通过")
     * @apiParam {String} merchantName <code>可选参数</code> 商家名称
     * @apiParam {Long} merchantId <code>可选参数</code> 商家ID
     * @apiParam {String} rechargeAccount <code>可选参数</code> 汇款帐号
     * @apiParam {date} beginDate <code>可选参数</code> 提交(审核)开始时间
     * @apiParam {date} endDate <code>可选参数</code> 提交(审核)结束时间
     * @apiParam {date} rechargeBeginDate <code>可选参数</code> 汇款开始时间
     * @apiParam {date} rechargeEndDate <code>可选参数</code> 汇款结束时间
     * @apiParam {date} rechargeDate <code>可选参数</code> 汇款时间
     * @apiParam {String=OUTLINE("线下支付")} payType <code>必选参数</code> 支付类型
     * @apiParam {BigDecimal} rechargeAmount <code>可选参数</code> 汇款金额
     *
     * @apiSuccess  {String} rechargeVoucher  汇款凭证
     * @apiSuccess {date} dateCreated  提交时间
     * @apiSuccess {date} dateAudited  审核时间
     * @apiSuccess {Long} merchantId  商家ID
     * @apiSuccess {String} merchantName  商家名称
     * @apiSuccess {String} rechargeStatus  状态
     * @apiSuccess {date} rechargeDate  汇款时间
     * @apiSuccess {BigDecimal} rechargeAmount  汇款金额
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": [
     *      {
     *        "id": 10,
     *        "dateCreated": "2016-06-13 18:28:41",
     *        "dateAudited": "2016-06-13 18:28:41",
     *        "merchantId": 12,
     *        "merchantName": "平台名称",
     *        "rechargeAccount": "3423453246345254",
     *        "rechargeDate": "2016-06-13",
     *        "rechargeAmount": "23.23",
     *        "rechargeStatus": "WAIT",
     *        "rechargeVoucher": "http://34345243.jpg"
     *      },
     *      ........　
     *   ]
     * }
     */
    @RequestMapping(value = Routes.MERCHANT_RECHARGE_AUDIT_PAGE, method = RequestMethod.GET)
    public JsonResult merchantRechargeAuditPage (HttpServletRequest request, MerchantRechargeFlowDto dto) {
        UserInfoDto userDto = userHelper.getSession(request);
        Long mallId = userDto.mall.getId();
        RestDoing doing = jsonResult -> {
            if(StringUtils.isBlank(dto.getPayType()) || MerchantPayType.OUTLINE != MerchantPayType.valueOf(dto.getPayType())){
                jsonResult.remind("支付类型 只允许 OUTLINE(\"线下支付\")\"",log);
                return;
            }

            if(StringUtils.isBlank(dto.getRechargeStatus()) || !EnumUtils.isValidEnum(MerchantRechargeStatus.class,dto.getRechargeStatus())){
                jsonResult.remind("审核状态为空 只允许 WAIT(\"待审核\"),AUDITED(\"已审核或者全部状态\"), SUCCESS(\"审核通过\"),FAIL(\"审核不通过\")",log);
                return;
            }

            PageResult<MerchantRechargeFlowDto> pageResult = merchantRechargeFlowRepository.findMerchantRechargePage(dto,mallId, this.getPage(dto.getPageNo(), dto.getPageSize()));
            pageResult.setUrl(Routes.MERCHANT_RECHARGE_AUDIT_PAGE);
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /v1/merchant/recharge/voucher M 商家充值审核详情
     * @apiGroup MERCHANT_RECHARGE
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     *
     *
     * @apiParam {Long} id <code>可选参数</code> 充值记录ID
     *
     * @apiSuccess  {String} rechargeVoucher  汇款凭证
     * @apiSuccess {date} dateCreated  提交时间
     * @apiSuccess {date} dateAudited  审核时间
     * @apiSuccess {Long} merchantId  商家ID
     * @apiSuccess {String} merchantName  商家名称
     * @apiSuccess {String} rechargeStatus  状态
     * @apiSuccess {date} rechargeDate  汇款时间
     * @apiSuccess {BigDecimal} rechargeAmount  汇款金额
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": [
     *      {
     *       "id": 10,
     *        "dateCreated": "2016-06-13 18:28:41",
     *        "dateAudited": "2016-06-13 18:28:41",
     *        "merchantId": 12,
     *        "merchantName": "平台名称",
     *        "rechargeAccount": "3423453246345254",
     *        "rechargeDate": "2016-06-13",
     *        "rechargeAmount": "23.23",
     *        "rechargeStatus": "WAIT",
     *        "rechargeVoucher": "http://34345243.jpg"
     *      },
     *      ........　
     *   ]
     * }
     */
    @RequestMapping(value = Routes.MERCHANT_RECHARGE_VOUCHER, method = RequestMethod.GET)
    public JsonResult merchantRechargeInfo (HttpServletRequest request, MerchantRechargeFlowDto dto) {
        RestDoing doing = jsonResult -> {
            if (dto.getId() == null) {
                jsonResult.remind(MerchantRechargeFlow.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }
            MerchantRechargeFlow merchantRechargeFlow = merchantRechargeFlowRepository.findOne(dto.getId());
            if (merchantRechargeFlow == null) {
                jsonResult.remind(MerchantRechargeFlow.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }
            jsonResult.data = merchantRechargeFlow;
        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /v1/merchant/recharge/audit M 商家充值审核
     * @apiGroup MERCHANT_RECHARGE
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {long} id <code>必选参数</code> 充值记录ID
     * @apiParam {String} rechargeStatus <code>必选参数</code> 状态 ：SUCCESS("审核通过"),FAIL("审核不通过")
     * @apiParam {String} remark <code>可选参数</code> 审核意见:审核不通过,审核意见不能为空
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功"
     * }
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @RequestMapping(value = Routes.MERCHANT_RECHARGE_AUDIT, method = RequestMethod.PUT)
    public JsonResult merchantRechargeAudit (HttpServletRequest request, @RequestBody MerchantRechargeFlowDto dto) {
        RestDoing doing = jsonResult -> {
            Long merchantRechargeFlowId = dto.getId();
            if (merchantRechargeFlowId == null) {
                jsonResult.remind(MerchantRechargeFlow.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }
            MerchantRechargeFlow merchantRechargeFlow = merchantRechargeFlowRepository.findOne(merchantRechargeFlowId);
            if (merchantRechargeFlow == null) {
                jsonResult.remind(MerchantRechargeFlow.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }
            if (merchantRechargeFlow.getRechargeStatus() != MerchantRechargeStatus.WAIT) {
                jsonResult.remind("此充值已审核",log);
                return;
            }
            String rechargeStatus = dto.getRechargeStatus();
            if (StringUtils.isBlank(rechargeStatus) || !EnumUtils.isValidEnum(MerchantRechargeStatus.class, rechargeStatus)) {
                jsonResult.remind("审核状态只允许 SUCCESS(\"审核通过\"),FAIL(\"审核不通过\")",log);
                return;
            }
            SysMessage message = null;
            String dateCreated = DateUtils.formatDate(merchantRechargeFlow.getDateCreated()) ;
            BigDecimal amount = merchantRechargeFlow.getRechargeAmount();
            Mall mall = mallSrv.findOne(merchantRechargeFlow.getMallId());
            String servicPhone = mall.getServiceTelephone();
            if (MerchantRechargeStatus.FAIL == MerchantRechargeStatus.valueOf(rechargeStatus)) {
                String remark = dto.getRemark();
                if (StringUtils.isBlank(remark)) {
                    jsonResult.remind("审核不通过的情况下, 审核意见不能为空",log);
                    return;
                }
                merchantRechargeFlow.setRemark(remark);

                String content = SysMessageConstants.M2B_MERCHANT_RECHARGE_AUDIT_UNPASS.getContent();
                content = MessageFormat.format(content, dateCreated, amount, remark, servicPhone);
                message = SysMessageHelper.SINGLETON.createMsgBean(SysMessageConstants.M2B_MERCHANT_RECHARGE_AUDIT_UNPASS, SysMessageType.FINANCE, content);

            } else if (MerchantRechargeStatus.SUCCESS == MerchantRechargeStatus.valueOf(rechargeStatus)) {

                Long merchantRechargeFlowMerchantId = merchantRechargeFlow.getMerchantId();
                Merchant merchant = merchantRepository.findOne(merchantRechargeFlowMerchantId);
                if (merchant == null) {
                    jsonResult.remind("商家不存在, 请查证信息",log);
                    return;
                }

                Long merchantFundId = merchant.getMerchantFundId();
                MerchantFund merchantFund = merchantFundRepository.findOne(merchantFundId);
                if (merchantFund == null) {
                    jsonResult.remind("商家账户存在异常, 请联系技术人员",log);
                    return;
                }
                //商家账户 充值金额增加、可用余额增加、总金额增加
                merchantRechargeFlowSrv.save(merchantRechargeFlow);

                String content = SysMessageConstants.M2B_MERCHANT_RECHARGE_AUDIT_PASS.getContent();
                content = MessageFormat.format(content, dateCreated, amount, servicPhone);
                message = SysMessageHelper.SINGLETON.createMsgBean(SysMessageConstants.M2B_MERCHANT_RECHARGE_AUDIT_PASS, SysMessageType.FINANCE, content);

            }
            merchantRechargeFlow.setRechargeStatus(MerchantRechargeStatus.valueOf(rechargeStatus));
            merchantRechargeFlow.setDateAudited(new Date());
            merchantRechargeFlowRepository.save(merchantRechargeFlow);


            Long merchantId = merchantRechargeFlow.getMerchantId();
            SysMessageHelper.SINGLETON.pushMsgByMallAndMerchantId(message, null, merchantId);
        };
        return doing.go(request, log);
    }
}
